const workModel = require('../models/workModel')

const resolveWorkList = (list) => {
  if (list.length == 0) return list
  // 1信息摸排   2商机跟进  3驻商工作
  const result = { xxmp: [], sjgj: [], zsgz: [] }
  list.forEach((item) => {
    if (item.workType == 1) {
      result.xxmp.push(item)
    } else if (item.workType == 2) {
      result.sjgj.push(item)
    } else {
      result.zsgz.push(item)
    }
  })
  return result
}

const resolveWorkObject = (obj) => {
  // 1信息摸排   2商机跟进  3驻商工作workType
  const xxmp = obj.xxmp.map((i) => {
    return { ...i, workType: 1 }
  })
  const sjgj = obj.sjgj.map((i) => {
    return { ...i, workType: 2 }
  })
  const zsgz = obj.zsgz.map((i) => {
    return { ...i, workType: 3 }
  })
  return [...xxmp, ...sjgj, ...zsgz]
}

const getWork = async (params) => {
  const works = await workModel.getDailyWork(params)
  if (works.length == 0) return {}
  const data = works[0]
  const items = await workModel.getAllItemsByWorkId(data.id)
  const worklist = resolveWorkList(items)
  return { ...data, ...worklist }
}

const getLastWork = async (params) => {
  const works = await workModel.getLastDailyWork(params)
  if (works.length == 0) return {}
  const data = works[0]
  const items = await workModel.getAllItemsByWorkId(data.id)
  const worklist = resolveWorkList(items)
  return { ...data, ...worklist }
}

const saveWork = async (params) => {
  if (params.id) return updateWork(params)
  else return saveNewWork(params)
}

const saveNewWork = async (params) => {
  const workList = resolveWorkObject(params)
  if (workList.length) {
    const [results] = await workModel.saveNewWork(params)
    const workId = results.insertId
    return await workModel.saveWorkList(workList, workId)
  } else {
    return await workModel.saveNewWork(params)
  }
}

const updateWork = async (params) => {
  const workList = resolveWorkObject(params)
  if (workList.length) {
    await workModel.updateWork(params)
    const workId = params.id
    await workModel.delWorkListByWorkId(workId)
    return await workModel.saveWorkList(workList, workId)
  } else {
    return await workModel.updateWork(params)
  }
}

const hasFinished = async (id) => {
  return await workModel.hasFinished(id)
}

const allFinished = async (date) => {
  const finishedUsers = await workModel.allFinished(date)
  const users = ['王海朝', '李嘉楠', '丛煜坤', '高伟祥']
  return users.filter((item) => !finishedUsers.includes(item))
}

module.exports = {
  getLastWork,
  getWork,
  saveWork,
  hasFinished,
  allFinished
}
